package com.chb.controller;

import com.alibaba.fastjson.JSON;
import com.chb.common.CommonConstants;
import com.chb.dto.ResultDto;
import com.chb.entity.SecurityUserInfo;
import com.chb.entity.SimpleUserDetails;
import com.chb.properties.SecurityConfigProperties;
import com.chb.redis.RedisService;
import com.chb.thread.FirstService;
import com.chb.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author CHB
 * @createTime 2022-8-22 15:51
 */
@Slf4j
@RestController
public class PortalController {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisService redisService;
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private SecurityConfigProperties securityConfigProperties;
    @PostMapping("/login")
    public String login(@RequestBody SecurityUserInfo securityUserInfo){
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(securityUserInfo.getName(), securityUserInfo.getPwd());
        Authentication authenticate = null;
        try{
            authenticate = authenticationManager.authenticate(authenticationToken);
        }catch (BadCredentialsException exception){
            log.info("登录失败");
        }
        if(authenticate == null){
            return "error";
        }
        // 生成token
        String token = jwtUtils.generateToken(securityUserInfo);
        // 获取数据库中用户信息
        SimpleUserDetails userDetails = (SimpleUserDetails) authenticate.getPrincipal();
        // 用户信息 存入redis
        redisService.set(String.format(CommonConstants.LOGIN_TOKEN_PREFIX,userDetails.getUsername().toUpperCase()),
                JSON.toJSONString(userDetails.getUserInfo()),securityConfigProperties.getJwtExpiration());
        return token;
    }
    @Resource
    private FirstService firstService;
    @PreAuthorize("hasAnyAuthority('admin','woman')")
    @GetMapping("/woman")
    public ResultDto<String> m1(){
        return ResultDto.success(firstService.he());
    }
}
